package database

import (
	"blog2/util"
)

type User struct {
	Id     int    `gorm:"column:id;primaryKey"`
	Name   string `gorm:"column:name"`
	PassWd string `gorm:"column:password"`
}

func (User) TableName() string {
	return "user"
}

var (
	_all_user_field = util.GormFields(User{})
)

func CreateUser(name, password string) {
	db := GetBlogDBConnection()
	passwordWithMd5 := util.MD5(password)
	if err := db.Create(&User{Name: name, PassWd: passwordWithMd5}); err != nil {
		util.LogRus.Errorf("Error creating user, name: %s, password: %s", name, password)
	} else {
		util.LogRus.Infof("User %s created successfully", name)
	}
}

func GetUserByName(name string) *User {
	db := GetBlogDBConnection()
	var user User
	if err := db.Select(_all_user_field).Where("name=?", name).First(&user).Error; err != nil {
		util.LogRus.Infof("Error getting user by name: %s, error: %s", name, err)
		return nil
	}
	return &user
}

func DeleteUser(name string) {
	db := GetBlogDBConnection()
	if err := db.Where("name=?", name).Delete(User{}).Error; err != nil {
		util.LogRus.Errorf("delete user %s failed: %s", name, err)
	}
}

func UpdateUserName(name, new_name string) {
	db := GetBlogDBConnection()
	if err := db.Model(&User{}).Where("name=?", name).Update("name", new_name).Error; err != nil {
		util.LogRus.Errorf("update user name %s failed: %s", name, err)
	}
}

func UpdateUserPassword(name, password, newPassword string) {
	db := GetBlogDBConnection()
	pass := util.MD5(password)
	newPass := util.MD5(newPassword)
	if err := db.Model(&User{}).Where("name=?", name).Where("password=?", pass).Update("password", newPass).Error; err != nil {
		util.LogRus.Errorf("update user password %s failed: %s", name, err)
	}
}

func IsUserExist(name string) bool {
	return GetUserByName(name) != nil
}
